package com.imooc.controller;

import com.imooc.constants.RedisConstant;
import com.imooc.dataobject.ProductCategory;
import com.imooc.dataobject.ProductInfo;
import com.imooc.service.CategoryService;
import com.imooc.service.ProductService;
import com.imooc.utils.ResultVOUtil;
import com.imooc.vo.ProductInfoVO;
import com.imooc.vo.ProductVO;
import com.imooc.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * FileName: BuyerProductController.java
 * Description: BuyerProductController
 *
 * @author HuangRI(874668739 @ qq.com)
 * @version 1.0
 * @date 2020/12/17
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    @RequestMapping("/list")
    // 缓存方式1-1
    @Cacheable(cacheNames = RedisConstant.CACHE_BUYER_PRODUCT_UP_LIST,
            key = RedisConstant.KEY_BUYER_PRODUCT,
            unless = "#result.getCode() != 0")
    public ResultVO list() {
        // 1.查询所有的上架商品
        List<ProductInfo> allUpProductList = this.productService.findUpAll();

        // 2.查询类目（一次性查询）
        List<Integer> categoryTypeList = allUpProductList.stream()
                .map(e -> e.getCategoryType())
                .collect(Collectors.toList());
        List<ProductCategory> categories = this.categoryService.findByCategoryTypeIn(categoryTypeList);

        // 3.数据拼装
        List<ProductVO> productVOs = new ArrayList<>();
        for (ProductCategory category : categories) {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(category.getCategoryName());
            productVO.setCategoryType(category.getCategoryType());

            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            for (ProductInfo productInfo : allUpProductList) {
                if (category.getCategoryType().equals(productInfo.getCategoryType())) {
                    ProductInfoVO productInfoVO = new ProductInfoVO();
                    BeanUtils.copyProperties(productInfo, productInfoVO);
                    productInfoVOList.add(productInfoVO);
                }
            }
            productVO.setProductInfoVOList(productInfoVOList);

            productVOs.add(productVO);
        }

        return ResultVOUtil.ok(productVOs);
    }

}
